package com.weiaibenpao.demo.chislim.ui.activity.running;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.PolylineOptions;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.BuildConfig;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.TwoPointLine;
import com.weiaibenpao.demo.chislim.bean.SportOverInfoBean;
import com.weiaibenpao.demo.chislim.db.entities.RunningRecord;
import com.weiaibenpao.demo.chislim.db.preferences.RunningPreferences;
import com.weiaibenpao.demo.chislim.service.RunningService;
import com.weiaibenpao.demo.chislim.tts.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.ui.widget.RunningDataView;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.PolyLinesUtils;
import com.weiaibenpao.demo.chislim.utils.RunningUtils;
import com.weiaibenpao.demo.chislim.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.query.Query;

public class ChinaOutRunActivity extends BaseOutdoorRunningActivity implements RunningDataView.OnUserActionListener {

    protected final int DRAW_LINE_CODE = 0x100;
    protected PolyLinesUtils polyLinesUtils;
    protected String code;
    protected float runDistance;
    protected int pointNum;
    protected int runPoint=0;
    protected float districtDistance;
    protected PolylineOptions options;
    protected ArrayList<LatLng> mLatLngList = new ArrayList<>();
    protected boolean isRunOneDistance=false;
    protected boolean isRunOver=false;
    protected List<TwoPointLine> twoPointLines;
    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PolyLinesUtils.POLYLINE_OVER_SUCCESS:
                    twoPointLines = (List<TwoPointLine>) msg.obj;
                    if (twoPointLines != null && twoPointLines.size() != 0) {
                        pointNum = twoPointLines.size();
                        if ((getRunTotal()) > 0) {
                            drawLine(getRunTotal());
                            Logger.e("getRunTotal():"+getRunTotal());

                        }
                    }
                    break;
                case DRAW_LINE_CODE:
                    aMap.addPolyline((PolylineOptions) msg.obj);
                    Logger.e("startRun:"+options.getPoints().size());

                    break;

            }
        }
    };
    private LatLng mLatLng;
    protected float beforeDis;
    protected float sportType;
    protected String district;
//    protected StringBuilder mLocusPhoto = new StringBuilder();       //轨迹
//    protected StringBuilder mFrequencyPhoto = new StringBuilder();   //步频图
//    protected StringBuilder mStridePhoto = new StringBuilder();      //步幅图
//    protected StringBuilder mPaceForm = new StringBuilder();         //配速列表
//    protected StringBuilder mAltitudePhoto = new StringBuilder();    //海拔图
    protected String mCalorie;
    protected String totalStep;

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, ChinaOutRunActivity.class);
//        intent.putExtra(Constant.CITY_CODE, code);
//        intent.putExtra(Constant.RUN_DISTANCE, runDistance);
//        intent.putExtra(Constant.DISTRICT_DISTANCE, districtDistance);
        context.startActivity(intent);

    }

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        code= RunningPreferences.getInstance().getDistrictCode();
        runDistance= RunningPreferences.getInstance().getRunDistance();
        districtDistance= RunningPreferences.getInstance().getDistrictDistance();
        district = RunningPreferences.getInstance().getDistrict();
        Logger.e("code=="+code);
        sportType = RunningPreferences.getInstance().getSportType();
        runningDataView.setOnUserActionListener(this);
        initPolyLine();
    }

    protected void initPolyLine() {
        polyLinesUtils = new PolyLinesUtils(this, aMap);
        polyLinesUtils.drawLine(code, mHandler);
        if (options == null) {
            options = new PolylineOptions();
            options.width(12).color(getResources().getColor(R.color.color_run));
        }
    }

    @Override
    protected void putExtraToServiceIntent(Intent serviceIntent) {
        super.putExtraToServiceIntent(serviceIntent);
        serviceIntent.putExtra(RunningService.RUNNING_ACTIVITY, getClass().getCanonicalName());
        serviceIntent.putExtra(RunningService.NEED_SAVE_RECORD, true);
        serviceIntent.putExtra(RunningService.NEED_EXTRA_DATA, true);
        serviceIntent.putExtra(RunningService.NEED_SAVE_STATE, true);
    }

    @Override
    protected void restoreDataDisplay() {
        super.restoreDataDisplay();
        showAddToWhiteListNotice();
//        code= RunningPreferences.getInstance().getDistrictCode();
//        runDistance= RunningPreferences.getInstance().getRunDistance();
//        districtDistance= RunningPreferences.getInstance().getDistrictDistance();

        Bundle bundle = new Bundle();
        bundle.putFloat(RunningService.DISTANCE, RunningPreferences.getInstance().getRunningDistance());
        bundle.putString(RunningService.CALORIE, RunningPreferences.getInstance().getRunningCalorie());
        bundle.putString(RunningService.PACE, RunningPreferences.getInstance().getRunningPace());

        runningDataView.setData(bundle);
        runningDataView.setTime(RunningUtils.getHmsTime((RunningPreferences.getInstance().getRunningTime())));
        restoreTraceData();
    }
    private void restoreTraceData() {
        Query<RunningRecord> query = mRunningRecordBox.query().build();
        List<RunningRecord> records = query.find();
        Logger.e("restoreTraceData records size is  "+records.size());
        if (records == null || records.size() == 0) {
            return;
        }
        int recordSize = records.size();
        List<LatLng> tempList = new ArrayList<>();
        for (int i = 0; i < recordSize; i++) {
            if(isDestroyed()) {
                return;
            }
            RunningRecord record = records.get(i);
            tempList.add(new LatLng(record.getLat(), record.getLng()));
        }
        mLatLngList.addAll(0, tempList);//保证历史数据一定在前面
    }

    /**
     * @param totalDis
     */
    protected void drawLine(float totalDis) {
        if (options.getPoints() != null) {
            options.getPoints().clear();
        }
        final int currentNum ;

        if (totalDis >= districtDistance) {
            currentNum = pointNum;
        }else {
            currentNum = (int) (pointNum * (totalDis / districtDistance));
        }
//           new Thread(new Runnable() {
//               @Override
//               public void run() {
//                   for (int i = runPoint; i < currentNum; i++) {
//                       options.addAll(twoPointLines.get(i).getLatLngs());
//                   }
//                   Message message=Message.obtain();
//                   message.obj=options;
//                   message.what=DRAW_LINE_CODE;
//                   mHandler.sendMessage(message);
//                   runPoint = currentNum;
//               }
//           }).start();

        for (int i = runPoint; i < currentNum; i++) {
                PolylineOptions options = new PolylineOptions();
                options.width(12).color(getResources().getColor(R.color.color_run)).zIndex(200);
                options.addAll(twoPointLines.get(i).getLatLngs());
                aMap.addPolyline(options);
        }
        runPoint = currentNum;




    }

    @Override
    public void onDataUpdated(Bundle data) {
        super.onDataUpdated(data);
        mCalorie = data.getString(RunningService.CALORIE);
        totalStep = data.getString(RunningService.STEP);

           mLatLng=data.getParcelable(RunningService.LAT_LNG);
           mLatLngList.add(mLatLng);
        if (!isRunOneDistance&&districtDistance-(getRunTotal())<=1){
            isRunOneDistance=true;
            SpeechUtil.getInstance().speak("加油，中国跑还剩最后1公里！");
        }
        if (getRunTotal()>districtDistance&&!isRunOver){
            isRunOver=true;
            SpeechUtil.getInstance().speak("恭喜，中国跑已完成！");
            drawLine(districtDistance);

        }
//        if(mapView.getVisibility() == View.VISIBLE){//只在地图可见时更新地图，否则不更新
//                updateMap();
//
//        }
        updateMap();

    }

    /**
     *
     * @return 已跑总里程
     */
    private float getRunTotal() {
        return mCurrentDistance/1000+runDistance;
    }


    @Override
    protected boolean shouldShowCurrentLocation() {
        return false;
    }



    @Override
    protected void updateMap() {
        super.updateMap();

        //当本次的距离大于更新之前的距离需要去绘制，减少内存的消耗
       if (!isRunOver&&mCurrentDistance>beforeDis){
           drawLine(getRunTotal());
           beforeDis=mCurrentDistance;
       }
    }
    @Override
    public void onRunningTime(int runningTime) {
        super.onRunningTime(runningTime);
        runningDataView.setTime(RunningUtils.getHmsTime(runningTime));
    }

    @Override
    protected void uploadRunningData() {
        super.uploadRunningData();
        Query<RunningRecord> query = mRunningRecordBox.query().build();
        List<RunningRecord> records = query.find();
        assembleDataFromDatabase(records);
        if(isDestroyed()){
            return;
        }
        if(!Utils.isNetWorkConnected()){
            Toast.makeText(this, getString(R.string.network_not_connected), Toast.LENGTH_SHORT).show();
            return;
        }
        doUpLoad();
    }
    private void assembleDataFromDatabase(List<RunningRecord> list) {

        List<RunningRecord> records  = list;
        for(int i=0;i<records.size();i++){
            RunningRecord record = records.get(i);
            String timeStr = String.valueOf(record.getTime());
                mLocusPhoto.append(String.valueOf(record.getLng())).append(":").append(String.valueOf(record.getLat())).append(":").append(record.getSpeed()).append(",");
                mStridePhoto.append(timeStr).append(":").append(record.getStride()).append(",");
            mFrequencyPhoto.append(timeStr).append(":").append(record.getFrequency()).append(",");
            //配速格式为 整公里数：配速：时间，
            if(!TextUtils.isEmpty(record.getKmPace())){
                mPaceForm.append(record.getKmValue()).append(":").append(record.getKmPace()).append(":").append(timeStr).append(",");
            }
            mAltitudePhoto.append(timeStr).append(":").append(record.getAltitude()).append(",");
        }
        if(BuildConfig.DEBUG) Logger.e("上传的数据"+"坐标--" + mLocusPhoto.toString() + "  步频--" + mFrequencyPhoto + " 步幅--" + mStridePhoto + "   配速--" + mPaceForm + "  海拔--" + mAltitudePhoto);
        if(BuildConfig.DEBUG) Logger.e("上传的数据"+"坐标size--" + mLocusPhoto.length() + "  步频size--" + mFrequencyPhoto.length() + " 步幅size--" + mStridePhoto.length() + "   配速size--" + mPaceForm.length() +
                "  海拔size--" + mAltitudePhoto.length());
    }

    protected void doUpLoad() {

       mPresenter.postRunData(userId,3, Constant.TYPE_CHINA,String.valueOf(marathonType),code,district,districtDistance,mCalorie,
              "",String.valueOf(mAltitudePhoto),String.valueOf(mFrequencyPhoto),String.valueOf(mStridePhoto),
               String.valueOf(mPaceForm), String.valueOf(mLocusPhoto),"",0,mTotalTime,totalStep,mCurrentDistance/1000);
    }
//    protected StringBuilder mLocusPhoto = new StringBuilder();       //轨迹
//    protected StringBuilder mFrequencyPhoto = new StringBuilder();   //步频图
//    protected StringBuilder mStridePhoto = new StringBuilder();      //步幅图
//    protected StringBuilder mPaceForm = new StringBuilder();         //配速列表
//    protected StringBuilder mAltitudePhoto = new StringBuilder();    //海拔图
    @Override
    public void onUploadDataSuccess(SportOverInfoBean sportInfoBean) {
        super.onUploadDataSuccess(sportInfoBean);
//        EventBus.getDefault().post(new DistrictBean("","",districtDistance,getRunTotal()/1000));
       ShareActivity.startSelf(this,sportInfoBean,"中国·室外",district);
       doFinish();
    }
}
